<template>
  <div>
    <van-nav-bar
      title="登录"
      left-arrow
      fixed
      placeholder
      z-index="999"
      @click-left="$router.back()"
    />

    <div class="loginPage">
      <div class="logo">
        <img src="../assets/logo.jpg" alt="" />
      </div>
    </div>
    <!--     -->

    <!-- 组件中放置插槽  -->
    <!-- @submit="onSubmit"  子传父 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        placeholder="用户名"
        :rules="regRules.username"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        placeholder="密码"
        :rules="regRules.password"
      />
      <div style="margin: 16px">
        <van-button round block type="info" color="#DB281F" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
    <div class="link">
      <router-link to="/reg">去注册</router-link>
    </div>
  </div>
</template>

<script>
import { Form } from "vant";
import { Field } from "vant";
import regRules from "@/utils/validator/reg";
export default {
  name: "login",
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
  },
  data() {
    return {
      username: "",
      password: "",
      regRules,
    };
  },
  methods: {
    //  提交的方法
    //  上边的拦截都过了 就能走这个函数
    onSubmit(val) {
      this.$http.post("/apis/user/pub/login", val).then((res) => {
        console.log(res);

        if (res.code == 0) {
          this.$toast("登录成功");
          let { token, tokenExpired, uid ,userInfo} = res;

          localStorage.setItem("xl-token", token);
          localStorage.setItem("xl-tokenExpired", tokenExpired);
          localStorage.setItem("xl-uid", uid);

          localStorage.setItem('xl-userInfo',JSON.stringify(userInfo)) //  昵称 头像这些放在这


          // 还需要把全局变量改了  

          //  XX 错误写法  this.userInfo  //  XXXXXX




          // 保存到全局变量  
          // 变量   刷新就没了    
          //  响应式的    数据变化能自动更新视图
          this.$root.userInfo = userInfo
          this.$root.token = token
          this.$root.uid = uid

          //   页面返回

          setTimeout((v) => {
            this.$router.go(-1);
          }, 800);
        } else {
          this.$toast(res.msg || "登录失败");
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.loginPage {
  .logo {
    width: 150px;
    height: 150px;
    margin: 50px auto 0;
    img {
      width: 150px;
      height: 150px;
    }
  }
}

/deep/ .van-field__body {
  border-radius: 30px;
  height: 50px;
  border: 1px solid #999;
  padding-left: 10px;
}

.link {
  padding: 10px;
}
</style>